﻿'use strict';

const fs = require('fs');

function addMapping(router, mapping) {
    for (const url in mapping) {

        if (url.startsWith('get_') || url.startsWith('post_')) {
            var method = url.split('_')[0],
                path = url.split('_')[1];

            router[method](path, mapping[url]);

            console.log(`register URL mapping: ${method.toUpperCase()} ${path}`);
        } else {
            // 无效的URL:
            console.log(`invalid URL: ${url}`);
        }

        if (url.startsWith('GET ')) {
            // 如果url类似"GET xxx":
            var path = url.substring(4);
            router.get(path, mapping[url]);
            console.log(`register URL mapping: GET ${path}`);
        } else if (url.startsWith('POST ')) {

            // 如果url类似"POST xxx":
            var path = url.substring(5);
            router.post(path, mapping[url]);
            console.log(`register URL mapping: POST ${path}`);

        }
    }
}

function addController(dir, router) {
    var files = fs.readdirSync(__dirname + '/controllers');

    var js_files = files.filter((f) => {
        return f.endsWith('.js');
    });
    for (const f of js_files) {
        console.log(`process controller: ${f}...`);

        //导入js文件
        let mapping = require(dir + '/controllers/' + f);
        addMapping(router, mapping);
    }
}

module.exports = function(dir) {
    let controllers_dir = dir || 'controllers', // 如果不传参数，扫描目录默认为'controllers'
        router = require('koa-router')();

    addController(controllers_dir, router);

    return router.routes();
}